/*
 * Copyright (c) 2024, Qi Yaolong.
 * dragon@hbu.edu.cn
 * HeBei University, China.
 * 
 * 简体中文
 * 保留所有权利。除非符合（遵守）以下条款，否则您不得使用此文件：
 * 
 * 禁止任何未经授权的个人或组织以任何形式将本程序及其附属资料、创新、创意、架构设计、算法、衍生作品
 * 等用于任何商业目的、盈利活动、各类竞赛(比赛)、直播教学、录播教学、线下课程、书籍编写、教材编写、
 * 会议、培训、公益活动、项目课题、毕业设计、毕业论文、学术论文等。
 * 
 * 本程序由版权持有人和贡献人“按原样”提供，不提供任何明示或暗示担保，包括但不局限于对适销性和特定
 * 用途适合性的暗示担保。在任何情况下，版权持有人或贡献人对因使用本程序而导致的任何直接、间接、附带、
 * 特殊、典型或后果性损害（包括但不限于购买替代商品或服务；使用损失、数据丢失或利润损失；业务中断）
 * 不承担任何责任，无论其如何产生，也不论其责任理论为何，无论是合同、严格责任还是侵权（包括疏忽或
 * 其他），即使已告知此类损害的可能性。
 * 
 * English
 * All rights reserved. You may NOT use this file except in compliance with the
 * following terms:
 * 
 * IT IS PROHIBITED FOR ANY UNAUTHORIZED PERSON OR ENTITY TO USE THIS PROGRAM AND 
 * ITS ANCILLARY DATA, INNOVATIONS, CONCEPTS, ARCHITECTURE DESIGN, ALGORITHMS, 
 * DERIVED WORKS, ETC., IN ANY FORM FOR COMMERCIAL PURPOSES, PROFIT-MAKING 
 * ACTIVITIES, VARIOUS COMPETITIONS (CONTESTS), LIVE TEACHING, PRE-RECORDED 
 * LESSONS, OFFLINE COURSES, BOOK WRITING, CONFERENCES, TRAININGS, PUBLIC WELFARE 
 * ACTIVITIES, PROJECTS, TOPICS, GRADUATION DESIGNS, DISSERTATIONS, THESES, AND 
 * OTHER APPLICATIONS.
 * 
 * THIS PROGRAM IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS PROGRAM, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "stdlib.h"
#include "ohos_init.h" 
#include "cmsis_os2.h" 

#include "wifi_device.h"
#include "radar_service.h"

#include "traffic_light.h"

#define RADAR_STATUS_CALI_ISO 4        
#define RADAR_STATUS_QUERY_DELAY 10000 

#define RADAR_API_NO_HUMAN 0       
#define RADAR_API_RANGE_CLOSE 50   
#define RADAR_API_RANGE_NEAR 100   
#define RADAR_API_RANGE_MEDIUM 200 
#define RADAR_API_RANGE_FAR 600    

typedef struct
{
    
    uint8_t times;
    
    uint8_t loop;
    
    uint8_t ant;
    
    uint8_t wave;
    
    uint8_t dbg_type;
    
    uint16_t period;
} radar_driver_para_t;

static void radar_set_driver_para_weakref(radar_driver_para_t *para) __attribute__((weakref("radar_set_driver_para")));

typedef struct
{
    uint8_t height;       
    uint8_t scenario;     
    uint8_t material;     
    uint8_t fusion_track; 
    uint8_t fusion_ai;    
} radar_sel_para_t;

static void radar_set_alg_ctrl_para_weakref(radar_sel_para_t *para) __attribute__((weakref("radar_set_alg_ctrl_para")));

typedef struct
{
    uint8_t d_th_1m;    
    uint8_t d_th_2m;    
    uint8_t p_th;       
    uint8_t t_th_1m;    
    uint8_t t_th_2m;    
    uint8_t b_th_ratio; 
    uint8_t b_th_cnt;   
    uint8_t a_th;       
} radar_alg_para_t;

static void radar_update_alg_param_weakref(radar_alg_para_t *para, uint8_t write_to_flash) __attribute__((weakref("radar_update_alg_param")));

static void start_sta(void)
{
    printf("STA try enable.\r\n");
    while (wifi_sta_enable() != ERRCODE_SUCC)
    {
        printf("STA enable fail, retry...\r\n");
        osal_msleep(100);
    }
}

static void radar_result_cb(radar_result_t *res)
{
    printf("[radar_result_cb] lower_boundary:%u, upper_boundary:%u, human_presence:%u\r\n",
           res->lower_boundary, res->upper_boundary, res->is_human_presence);
    printf("%s\r\n", res->is_human_presence == 1 ? "Human presence" : "No human presence");

    if (res->is_human_presence == 1)
    {
        if (res->lower_boundary == 0 && res->upper_boundary == RADAR_API_RANGE_NEAR)
        {
            red_led_on();
            yellow_led_on();
            green_led_on();
            printf("R 0-1 meters\r\n");
        }
        else if ((res->lower_boundary == RADAR_API_RANGE_NEAR && res->upper_boundary == RADAR_API_RANGE_MEDIUM))
        {
            red_led_off();
            yellow_led_on();
            green_led_on();
            printf("R 1-2 meters\r\n");
        }
        else
        {
            red_led_off();
            yellow_led_off();
            green_led_on();
            printf("R 2-6 meters\r\n");
        }
    }
    else
    {
        red_led_off();
        yellow_led_off();
        green_led_off();
    }
}

static void radar_init_para(void)
{
    radar_driver_para_t para;
    para.ant = 0;                         
    para.dbg_type = 1;                    
    para.loop = 8;                        
    para.period = 5000;                   
    para.times = 0;                       
    para.wave = 2;                        
    radar_set_driver_para_weakref(&para); 

}

static void RadarDemoTask(void)
{
    
    traffic_light_init();

    start_sta();
    osal_msleep(1000); 

    uapi_radar_register_result_cb(radar_result_cb);

    radar_init_para();

    uapi_radar_set_status(RADAR_STATUS_CALI_ISO);
    
    while (1)
    {
        
        uapi_radar_set_delay_time(8);

        osal_msleep(RADAR_STATUS_QUERY_DELAY); 

        uint8_t sts;
        uapi_radar_get_status(&sts);

        uint16_t time;
        uapi_radar_get_delay_time(&time);

        uint16_t iso;
        uapi_radar_get_isolation(&iso);

        printf("雷达状态:%s, 退出延迟时间:%u, 天线隔离度:%u\r\n",
               sts == RADAR_STATUS_RUNNING ? "工作中" : "未工作", time, iso);
    }
}

static void RadarDemoEntry(void)
{
    
    osThreadAttr_t attr;
    attr.name = "RadarDemoTask";
    attr.stack_size = 1024 * 10;
    attr.priority = osPriorityNormal;

    if (osThreadNew(RadarDemoTask, NULL, &attr) == NULL)
    {
        printf("[RadarDemoEntry] Falied to create RadarDemoTask!\n");
    }
}

APP_FEATURE_INIT(RadarDemoEntry);
